const express = require('express')
const router = express.Router()
const {
    insertShopCart,
    getShopCartList,
    removeShopCartList,
    modifyShopCartNum,
    modifyShopCartState,
    modifyAllShopCartState,
} = require('../../model/mongo')

const multipart = require('../../middleware/content-type/multypart')

router.use(multipart())
router.post('/list', async (req, res) => {
    const result = {
        code: 200,
        msg: '获取购物车列表'
    }
    const { userid } = req.body
    result.data = await getShopCartList(userid)
    res.send(JSON.stringify(result))
})

router.post('/add', async (req, res) => {
    let { userid, proid, size, num } = req.body
    let result = {
        code: 200,
        msg: '插入购物车成功'
    }
    if (!userid) {
        result.msg = 'userid为null'
        res.send(JSON.stringify(result))
        return
    }
    result.msg = await insertShopCart({ userid, proid, size, num })
    res.send(JSON.stringify(result))
})

router.post('/updatenum', async (req, res) => {
    const { cartid, num } = req.body
    const result = {
        code: 200,
        msg: ''
    }
    result.msg = await modifyShopCartNum(cartid, Number(num))
    res.send(JSON.stringify(result))
})

router.post('/selectOne', async (req, res) => {
    let { cartid, flag } = req.body
    let result = {
        code: 200,
        msg: ''
    }
    if (flag === 'true') {
        flag = true
    }
    if (flag === 'false') {
        flag = false
    }
    result.msg = await modifyShopCartState(cartid, flag)
    res.send(JSON.stringify(result))
})

router.post('/selectall', async (req, res) => {
    let { userid, flag } = req.body
    let result = {
        code: 200,
        msg: ''
    }
    if (flag === 'true') {
        flag = true
    }
    if (flag === 'false') {
        flag = false
    }
    result.msg = await modifyAllShopCartState(userid, flag)
    res.send(JSON.stringify(result))
})

router.post('/remove', async (req, res) => {
    let { cartid } = req.body
    let result = {
        code: 200,
        msg: '移除购物车记录'
    }
    try {
        result.msg = await removeShopCartList(cartid)
    } catch (err) {
        result.code = 404
        result.msg = err
    }
    res.send(result)
})

module.exports = router
